const _image64 = require("utils/image64.js")
const api = require("server/Api.js")
const _user = require("utils/User.js")
const util = require("utils/util.js")
const QQMapWX = require('utils/qqmap-wx-jssdk.min.js');

App({
  onLaunch: function() {

    this.checkUpdate();

    this.globalData.qqmapsdk = new QQMapWX({
      key: this.globalData.wxMapKey
    });

    let custom = tt.getMenuButtonBoundingClientRect();

    // 获取系统状态栏信息
    tt.getSystemInfo({
      success: e => {
        this.globalData.windowWidth = e.windowWidth;
        this.globalData.rpxToPxBl = e.windowWidth / 750;
        this.globalData.StatusBar = e.statusBarHeight;
        this.globalData.CustomBar = e.windowHeight < 400 ? 32 : 44;
        this.globalData.Custom = custom;
      }
    })

    //默认头像
    this.globalData.defaultHeadUrl = _image64.defaultHeadView;

    //微信快速登录
    let userBean = _user.getUser();
    if (userBean && userBean.consumerId) {
      this.globalData.userBean = userBean;
    }


  },
  //更新
  checkUpdate: function(e) {
  //   if (wx.canIUse('getUpdateManager')) {
  //     const updateManager = wx.getUpdateManager()
  //     updateManager.onCheckForUpdate(function(res) {
  //       console.log('onCheckForUpdate====', res)
  //       if (res.hasUpdate) {
  //         console.log('res.hasUpdate====')
  //         updateManager.onUpdateReady(function() {
  //           wx.showModal({
  //             title: '更新提示',
  //             content: '新版本已经准备好，是否重启应用？',
  //             success: function(res) {
  //               console.log('success====', res)
  //               if (res.confirm) {
  //                 updateManager.applyUpdate()
  //               }
  //             }
  //           })
  //         })
  //         updateManager.onUpdateFailed(function() {
  //           wx.showModal({
  //             title: '已经有新版本了哟~',
  //             content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
  //           })
  //         })
  //       }
  //     })
  //   }
  },
  //微信登录
  wxLogin: function() {
    let that = this;
    // 登录
    return new Promise(function(success, fail) {
      wx.login({
        success: res => {
          if (res.code) {
            success(res.code)
          } else {
            fail("获取Code失败")
          }
        }
      })
    }).then(code => {
      let that = this;
      let companyId = that.globalData.companyId;
      let platformId = that.globalData.platformId;
      return api.checkLogin(code, companyId, platformId);
    })
  },
  //头条登录
  ttLogin: function() {
    let that = this;
    // 登录
    return new Promise(function(success, fail) {
      tt.login({
        success: res => {
          if (res.code) {
            success(res.code)
          } else {
            fail("获取Code失败")
          }
        }
      })
    }).then(code => {
      let that = this;
      let companyId = that.globalData.companyId;
      let platformId = that.globalData.platformId;
      return api.checkLogin(code, companyId, platformId);
    })
  },
  //长文本提示框
  showToast: function(str) {
    if (typeof str != "string") return;
    tt.showToast({
      title: str,
      icon: 'none',
      duration: 3000,
    });
  },
  showLoading() {
    tt.showLoading({
      title: '请稍后',
    })
  },
  //返回首页
  backHome: function() {
    let pages = getCurrentPages();
    tt.navigateBack({
      delta: pages.length - 1,
    })

  },
  copyTxt: function(e) {
    tt.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function(res) {
        tt.getClipboardData({
          success: function(res) {
            tt.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },
  setMtoKm: function(m) {
    if (m > 1000) {
      return (m / 1000).toFixed(1) + "km";
    }
    return m.toFixed(1) + "m";
  },
  setBuyExponent: function(m) {
    if (!m) {
      return "0"
    } else if (m < 1000) {
      return m;
    } else if (m < 10000) {
      return (m / 1000).toFixed(1) + "k"
    } else {
      return (m / 10000).toFixed(1) + "w"
    }
  },
  makePhoneCall(n) {
    var that = this;
    tt.makePhoneCall({
      phoneNumber: n,
      fail() {
        that.showToast("拨打失败")
      }
    })
  },
  resetImageUrl(url, w, h, bgColor) {
    w = parseInt(this.globalData.rpxToPxBl * w);
    h = parseInt(this.globalData.rpxToPxBl * h);
    return url + `?x-image-process=image/resize,m_pad,limit_0` + (w ? `,w_${w}` : '') + (h ? `,h_${h}` : '') + (bgColor ? `,color_${bgColor}` : '')
  },
  resetImageUrlByPx(url, w, h, bgColor) {
    return url + `?x-image-process=image/resize,m_pad,limit_0` + (w ? `,w_${w}` : '') + (h ? `,h_${h}` : '') + (bgColor ? `,color_${bgColor}` : '')
  },
  setTabBarBadge() {
    if (this.globalData.cartCount > 0) {
      tt.setTabBarBadge({
        index: 1,
        text: '' + this.globalData.cartCount
      })
    } else {
      // tt.removeTabBarBadge({
      //   index: 1,
      // })
    }
  },
  downloadFile(url) {
    return new Promise((resolve, reject) => {
      tt.downloadFile({
        url: url,
        success(res) {
          if (res.statusCode === 200) {
            resolve(res)
          } else {
            reject(res)
          }
        },
        fail(res) {
          reject(res)
        }
      })
    });
  },
  getZtDate(dateStr, day) {
    let date = new Date();
    if (dateStr) {
      date = util.stringToDate(dateStr)
    }
    // if (!day) {
    //   day = 1;
    // }
    // if (date.getHours >= 22) {
    //   date = new Date(date.getTime() + (day + 1) * 24 * 60 * 60 * 1000)
    // } else {
    //   date = new Date(date.getTime() + day * 24 * 60 * 60 * 1000)
    // }
    return util.formatTime(date, "MM/dd")
  },
  getBuyTime(str) {
    str = str.replace("T", " ");
    return str.split(".")[0]
  },
  globalData: {
    shopId: 0,
    userShopId: [{
      id: 59
    }],
    //userShopId:[],
    cartCount: 0,
    shareUserId: "",
    loginDone: false,
    rpxToPxBl: 0.5,
    windowWidth: 350,
    qqmapsdk: undefined,
    addressName: "",
    cityName: "",
    lat: 0,
    lng: 0,
    indexCartUpdated: false,
    cartUpdated: false,
    cartGoodsNum: 0,
    userInfo: null,
    userBean: null,
    defaultHeadUrl: "",
    appid: 'wx079b0308af7f034b',
    // companyId: '3171776001692663894', //租户ID
    // platformId: '9609977215975480', //平台ID
    companyId: '3171776001692663893', //租户ID
    platformId: '3189609977215975481', //平台ID
    wxMapKey: "QFQBZ-KOEW6-MZXSA-MTYC6-URQZ6-OLBCJ"
  }
})